package com.idea.relax.mybatis.page;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

/**
 * @className: PageResVO
 * @description:
 * @author: salad
 * @date: 2023/4/29
 **/
@Data
public class PageResVO<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	@ApiModelProperty("数据")
	private List<T> records = Collections.emptyList();

	@ApiModelProperty("当前页")
	private Long current;

	@ApiModelProperty("页大小")
	private Long size;

	@ApiModelProperty("分页量")
	private Long pages;

	@ApiModelProperty("数据总数")
	private Long total;

	public PageResVO() {
	}

	public PageResVO(List<T> records, Long current, Long size, Long pages, Long total) {
		this.records = records;
		this.current = current;
		this.size = size;
		this.pages = pages;
		this.total = total;
	}

	public static <T> PageResVO<T> empty() {
		return new PageResVO<T>();
	}

	/**
	 * IPage转换为PageResVO
	 *
	 * @param page
	 * @param <T>
	 * @return
	 */
	public static <T> PageResVO<T> of(IPage<T> page) {
		PageResVO<T> pageResVO = new PageResVO<T>();
		pageResVO.setCurrent(page.getCurrent());
		pageResVO.setSize(page.getSize());
		pageResVO.setTotal(page.getTotal());
		pageResVO.setPages(page.getPages());
		pageResVO.setRecords(page.getRecords());
		return pageResVO;
	}

	/**
	 * IPage转换为PageResVO
	 *
	 * @param page
	 * @param mapper
	 * @param <T>
	 * @param <R>
	 * @return
	 */
	public static <T, R> PageResVO<R> of(IPage<T> page, Function<T, R> mapper) {
		List<R> records = new ArrayList<>();
		for (T record : page.getRecords()) {
			records.add(mapper.apply(record));
		}
		return new PageResVO<R>(records, page.getCurrent(), page.getSize(), page.getPages(), page.getTotal());
	}

}
